<template>
  <a-card class="content" title="实时定位"  :bordered="false">
    <!-- <button @click="ad">adfa</button>
    <button @click="transTimeManageV32">transTimeManageV3</button>
    <button @click="goodsTransferTrack2">goodsTransferTrack</button> -->

    <div ref="locationMapRef" style="height: 79vh; width: 100%">
      <div class="map_div">
        <div class="arrow" @click="arrowShow = !arrowShow"><caret-up-outlined v-if="arrowShow" /><caret-down-outlined
            v-if="!arrowShow" /></div>
        <div class="cars" v-if="arrowShow">
          <template v-for="(item, index) in car_set.list" :key="index">
            <div :class="['cars_info', item.id == selectId? 'select': '']" @click="car_info_click(item.id)">
              <div class="cars_info_title">{{ item.vno }}</div>
              <div class="cars_info_item">客户:{{ item.customer }}</div>
              <div class="cars_info_item">
                <template v-for="(item2, index2) in item.factoryAddress" :key="index2">
                  地址{{ index2 + 1 }}:{{ item2.factoryAddress }}
                </template>
              </div>
              <div class="cars_info_item">订单状态:{{ item.carState }}</div>
            </div>
            <a-divider />
          </template>
        </div>
      </div>
    </div>
    <!-- <div ref="locationMapRef" style="height: 360px; max-width: 800px"></div> -->
  </a-card>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';
import { MAP_KEY, API_BASE_URL, WEBSOCKET_URL } from '@/config/setting';
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons-vue';

import { trajectory, transTimeManageV3, goodsTransferTrack, carMapper } from '@/api/order/mapper';



const themeStore = useThemeStore();
const { darkMode } = storeToRefs(themeStore);

//
const locationMapRef = ref(null);

// 官网底部地图的实例
let mapInsLocation;

//车辆图层集合
let carMarks = reactive([]);
let arrowShow = ref(false)
let selectId = ref(0)
let car_set = reactive({ list: [] })

/* 渲染官网底部地图 */
const renderLocationMap = () => {
  AMapLoader.load({
    key: MAP_KEY,
    version: '2.0',
    plugins: ['AMap.InfoWindow', 'AMap.Marker']
  })
    .then((AMap) => {
      // 渲染地图
      const option = {
        zoom: 14, // 初缩放级别
        center: [121.633815, 29.840605], // 初始中心点
        mapStyle: darkMode.value ? 'amap://styles/dark' : void 0
      };
      mapInsLocation = new AMap.Map(locationMapRef.value, option);

      //默认把车子显示在地图上  通过webSocket
      carMapper()
      const icon = new AMap.Icon({
        // size: new AMap.Size(61, 42),
        image:
          // '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
          API_BASE_URL + '/file/20230517/a.png?path2=chf_setting',
        imageSize: new AMap.Size(61, 42),
      });
      //灰色车子图标
      const icon_gray = new AMap.Icon({
        // size: new AMap.Size(61, 42),
        image:
          // '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
          API_BASE_URL + '/file/20230517/b.png?path2=chf_setting',
        imageSize: new AMap.Size(61, 42),
      });

      const addMarks = () => {
        if (car_set.list) {
          carMarks.forEach(ele => {
            mapInsLocation.remove(ele.marker);
          })
          carMarks.length = 0
          car_set.list.forEach(ele => {
            // ele.lon = ele.lon + 0.001
            // ele.lat = ele.lat - 0.0001
            //货车图标
            const marker = new AMap.Marker({
              icon: ele.spd=='0.0'?icon_gray: icon,
              position: [ele.lon, ele.lat],
              offset: new AMap.Pixel(-26, -13),
              extData: {
                ele
              },
              angle: ele.drc,
            });
            marker.setMap(mapInsLocation);
            carMarks.push({ 'marker': marker, 'type': 'marker', "car": ele })
            marker.on('click', () => {
              infoWindow.open(mapInsLocation, [ele.lon , ele.lat + 0.0]);
              mapInsLocation.panTo([ele.lon + 0.0, ele.lat + 0.0]);
            });
            // 创建信息窗体
            const infoWindow = new AMap.InfoWindow({
              offset: new AMap.Pixel(-0, -13),
              content: `
                <div style="width: 300px; ">
                  <div style="display: flex; justify-content: center;width: 300px;">
                    <div div style="color: #ffffff;background-color: #C02722;padding: 2px;width: 300px;margin-top: 15px;">${ele.vno}</div>
                  </div>
                  <div style="padding-left:0px;margin-top:0px; display: flex;justify-content:space-between;">
                    <div>${ele.driver}</div>
                    <div>${ele.driverPhone}</div>
                  </div>
                  <a-divider />
                  <div style="padding-left:0px;margin-top:0px;">时间:${ele.factoryPackDate}</div>
                  <div style="padding-left:0px;margin-top:0px;">客户:${ele.customer}</div>
                  <div style="padding-left:0px;margin-top:0px;">提单号:${ele.billOfLading}</div>
                  <div style="padding-left:0px;margin-top:0px;">${ele.adr}</div>
                  <div style="padding-left:0px;margin-top:0px;">车速:${ele.spd} km/h</div>
                </div>
              `
            });

          });
        }
      }

      let socket;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        // console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket(WEBSOCKET_URL+"/webSocket/mapper".replace("http", "ws"));
        // socket = new WebSocket("ws://localhost:4337/webSocket/mapper".replace("http", "ws"));
        //打开事件
        socket.onopen = function () {
          //console.log("Socket 已打开");
          //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        socket.onmessage = function (msg) {
          if (msg.data) {
            car_set.list = JSON.parse(msg.data)
            addMarks()
          }
          //发现消息进入    开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function () {
          //console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          // console.log("Socket发生了错误");
          //此时可以尝试刷新页面
        }
      }
    })
    .catch((e) => {
      console.error(e);
    });
};

const car_info_click = (billId) => {
  selectId.value=billId
  carMarks.forEach(ele => {
    if (ele.car.id == billId) {
      ele.marker.emit('click', { target: ele.marker });
      // ele.marker.setPosition([ele.car.lon + 0.0, ele.car.lat + 0.0]);
      return false;
    }
  })
}

const transTimeManageV32 = () => {
  transTimeManageV3({ 'vnos': '浙B5G713_2,浙B86H62_2,浙B3W386_2' }).then((msg) => {
    // transTimeManageV3({ 'vnos': '陕YH0009_2' }).then((msg) => {
  }).catch((e) => {
    message.error(e.message);
  });
}

const goodsTransferTrack2 = () => {
  // goodsTransferTrack({'vclN': '浙B5G713', 'qryBtm': '2023-05-19 01:01:01', 'qryEtm': '2023-05-19 20:01:01'}).then((msg) => {
  goodsTransferTrack({ 'vclN': '陕YH0009', 'qryBtm': '2023-05-19 01:01:01', 'qryEtm': '2023-05-19 20:01:01' }).then((msg) => {
  }).catch((e) => {
    message.error(e.message);
  });
}

const ad = () => {
  trajectory({ 'vno': '陕YH0008_2', 'date1': '2023-05-19 01:01:01', 'date2': '2023-05-19 20:01:01' }).then((msg) => {
    message.success(msg);
  }).catch((e) => {
    message.error(e.message);
  });
}

/* 渲染地图 */
onMounted(() => {
  renderLocationMap();
});

/* 销毁地图 */
onUnmounted(() => {
  if (mapInsLocation) {
    mapInsLocation.destroy();
  }
});

/* 同步框架暗黑模式切换 */
watch(darkMode, (value) => {
  if (mapInsLocation) {
    if (value) {
      mapInsLocation.setMapStyle('amap://styles/dark');
    } else {
      mapInsLocation.setMapStyle('amap://styles/normal');
    }
  }
});
</script>


<style lang="less" scoped>
.content {
  background-color: #fff;
}
.map_div {
  background-color: #fff;
  width: 320px;
  position: absolute;
  z-index: 999999;
  right: 0px;
  top: 0px;

  .arrow {
    display: flex;
    justify-content: center;
    cursor: pointer;
  }

  .cars {
    overflow: scroll;
    height: 400px;
    color: #000;

    .cars_info {
    }
    .select{
      background: rgba(71, 118, 200, 0.15);
    }
    .cars_info_title {
      color: #0022ff;

      font-weight: bold;
      font-size: 15px;
      padding-left: 10px;
    }

    .cars_info_item {
      padding-left: 10px;
      font-size: 14px;
      color: #333333;
      margin-top: 8px
    }
  }
}
</style>